package com.weirong.smartvault.backservice.service;

import com.weirong.smartvault.dao.ForeignCurrencyRequestRepository;
import com.weirong.smartvault.entity.ForeignCurrencyRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import java.util.Date;

/**
 * 于2017/12/11由 KFEB4 创建 .
 */
@Service
public class ForeignCurrencyRequestServiceImpl implements ForeignCurrencyRequestService{
    @Autowired
    ForeignCurrencyRequestRepository foreignCurrencyRequestRepository;
    @Override
    public Page<ForeignCurrencyRequest> findAllByCreateTimeBetweenWithPageing(Date start, Date end, Integer page, Integer count) {
        Specification<ForeignCurrencyRequest> specification = (root, criteriaQuery, criteriaBuilder) -> {
            Path<Date> time = root.get("requestDate");
            Predicate predicate = criteriaBuilder.between(time,start,end);
            return criteriaBuilder.and(predicate);
        };

        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(page, count, sort);
        return foreignCurrencyRequestRepository.findAll(specification,pageable);

    }

    @Override
    public long countByCreateTimeBetween(Date start, Date end) {
        Specification<ForeignCurrencyRequest> specification = (root, criteriaQuery, criteriaBuilder) -> {
            Path<Date> time = root.get("deliveryTime");
            Predicate predicate = criteriaBuilder.between(time,start,end);
            return criteriaBuilder.and(predicate);
        };
        return foreignCurrencyRequestRepository.count(specification);
    }
}
